using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MiniAspNetCore
{
    /// <summary>
    /// web主机建造者
    /// </summary>
    public class WebHostBuilder : IWebHostBuilder
    {
        /// <summary>
        /// 服务提供者
        /// </summary>
        private IServer _server;
        /// <summary>
        /// 缓存中间件配置委托
        /// </summary>
        private readonly List<Action<IApplicationBuilder>> _configures = new List<Action<IApplicationBuilder>>();

        /// <summary>
        /// 构建web主机
        /// </summary>
        /// <returns>web主机</returns>
        public IWebHost Build()
        {
            IApplicationBuilder builder = new ApplicationBuilder(); // 实例化应用构建者
            foreach (Action<IApplicationBuilder> configure in _configures) // 循环添加应用中间件
            {
                configure(builder);
            }

            return new WebHost(_server, builder.Build()); // 构建应用管道并结合服务提供者实例化web主机
        }

        /// <summary>
        /// 配置中间件
        /// </summary>
        /// <param name="configure">配置中间件委托</param>
        /// <returns>web主机建造者</returns>
        public IWebHostBuilder Configure(Action<IApplicationBuilder> configure)
        {
            _configures.Add(configure); // 缓存配置中间件委托
            return this;
        }

        /// <summary>
        /// 配置服务
        /// </summary>
        /// <param name="server">待使用的服务</param>
        /// <returns>web主机建造者</returns>
        public IWebHostBuilder UseServer(IServer server)
        {
            _server = server;
            return this;
        }

        /// <summary>
        /// 使用HttpListener服务
        /// </summary>
        /// <param name="urls">HttpListener服务的监听地址</param>
        /// <returns>web主机建造者</returns>
        public IWebHostBuilder UseHttpListener(params string[] urls)
        {
            _server = new HttpListenerServer(urls);
            return this;
        }
    }
}
